package com.zstack;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dalin.common.clazz.Clazz;
import com.dalin.common.clazz.PropertyList;
import com.dalin.common.utils.StringUtils;
import com.dalin.common.utils.TextUtils;

public class CodeMain {
	private static String baseUrl = "http://10.10.182.170:8080/zstack/api/";
	private void aa() {
		//iMonitor.monitorRouterInfo(arg0)
	}
	
	public static void main(String[] args) {
		System.out.println(SHA512("password"));
	}

	private static String SHA512(final String strText) {
		// 返回值
		String strResult = null;

		// 是否是有效字符串
		if (strText != null && strText.length() > 0) {
			try {
				// SHA 加密开始
				// 创建加密对象 并傳入加密類型
				MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
				// 传入要加密的字符串
				messageDigest.update(strText.getBytes());
				// 得到 byte 類型结果
				byte byteBuffer[] = messageDigest.digest();

				// 將 byte 轉換爲 string
				StringBuffer strHexString = new StringBuffer();
				// 遍歷 byte buffer
				for (int i = 0; i < byteBuffer.length; i++) {
					String hex = Integer.toHexString(0xff & byteBuffer[i]);
					if (hex.length() == 1) {
						strHexString.append('0');
					}
					strHexString.append(hex);
				}
				// 得到返回結果
				strResult = strHexString.toString();
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
		}

		return strResult;
	}
	 

	public static void buildResClazz(String njlMethodName, String body) throws Exception {
		PropertyList propertyList = new PropertyList();
		String s = "identity";
		if (njlMethodName.contains("Vm")) {
			s = "vm";
		} else if (njlMethodName.contains("Volume")) {
			s = "volume";
		} else if (njlMethodName.contains("Host")) {
			s = "host";
		} else if (njlMethodName.contains("Zone")) {
			s = "zone";
		} else if (njlMethodName.contains("Image")) {
			s = "image";
		} else if (njlMethodName.contains("Vip")) {
			s = "vip";
		} else if (njlMethodName.contains("Cluster")) {
			s = "cluster";
		} else if (njlMethodName.contains("L3")) {
			s = "network.l3";
		} else if (njlMethodName.contains("Offering")) {
			s = "configuration";
		}
		String zstackJsonStr =  "{\"org.zstack.header."+s
				+".API"+njlMethodName+"Msg\":"
				+body+"}";
		System.out.println("req---->"+zstackJsonStr);
		String ss = sendPost(baseUrl,zstackJsonStr);
		System.out.println("res==="+ss);
		JSONObject jo = JSON.parseObject(ss);
		jo = JSON.parseObject(jo.get("result").toString());
		String replyKey = jo.keySet().iterator().next();
		jo = JSON.parseObject(jo.get(replyKey).toString());
		JSONArray ja = null;
		if (jo.get("inventories") != null) {
	    	ja = JSON.parseArray(jo.get("inventories").toString());
	    	List<Map<String, Object>> sss = JSON.parseObject(jo.get("inventories").toString(), List.class);
	    	System.out.println(sss.size());
	    	jo = JSON.parseObject(ja.get(0).toString());
	    } else {
	    	jo = JSON.parseObject(jo.get("inventory").toString());
	    }
		Map<String, Object> m = JSON.parseObject(jo.toJSONString(), Map.class);

		for (String key : jo.keySet()) {
			propertyList.add(jo.get(key).getClass().toString().replace("class java.lang.", ""), key, "");
		}
		System.out.println();
		Clazz myClazz = new Clazz();
		myClazz.setPropertyList(propertyList);
		myClazz.setPackageName("com.skycloud.sample.vo");
		myClazz.setClassName(StringUtils.toUpperCamelCase(njlMethodName)
				+ "Res");
		TextUtils.overwriteToText(myClazz.toString(), new File(
				"D:/ews/cutedalin/src/com/zstack/code/" + myClazz.getClassName()
						+ ".java"));
	}
	
	 public static String sendGet(String url) {
	        String result = "";
	        BufferedReader in = null;
	        try {
	            String urlNameString = url;
	            URL realUrl = new URL(urlNameString);
	            // 打开和URL之间的连接
	            URLConnection connection = realUrl.openConnection();
	            // 设置通用的请求属性
	            connection.setRequestProperty("Accept", "*/*");
	            connection.setRequestProperty("Connection", "keep-alive");
	            connection.setRequestProperty("User-Agent",
	                    "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0");
	            // 建立实际的连接
	            connection.connect();
	            // 获取所有响应头字段
	            Map<String, List<String>> map = connection.getHeaderFields();
	            // 遍历所有的响应头字段
	            for (String key : map.keySet()) {
	                System.out.println(key + "--->" + map.get(key));
	            }
	            // 定义 BufferedReader输入流来读取URL的响应
	            in = new BufferedReader(new InputStreamReader(
	                    connection.getInputStream()));
	            String line;
	            while ((line = in.readLine()) != null) {
	                result += line;
	            }
	        } catch (Exception e) {
	            System.out.println("发送GET请求出现异常！" + e);
	            e.printStackTrace();
	        }
	        // 使用finally块来关闭输入流
	        finally {
	            try {
	                if (in != null) {
	                    in.close();
	                }
	            } catch (Exception e2) {
	                e2.printStackTrace();
	            }
	        }
	        return result;
	    }

	    /**
	     * 向指定 URL 发送POST方法的请求
	     * 
	     * @param url
	     *            发送请求的 URL
	     * @param param
	     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	     * @return 所代表远程资源的响应结果
	     */
	    public static String sendPost(String url, String param) {
	        PrintWriter out = null;
	        BufferedReader in = null;
	        String result = "";
	        try {
	            URL realUrl = new URL(url);
	            // 打开和URL之间的连接
	            URLConnection conn = realUrl.openConnection();
	            // 设置通用的请求属性
	            conn.setRequestProperty("accept", "*/*");
	            conn.setRequestProperty("connection", "Keep-Alive");
	            conn.setRequestProperty("user-agent",
	                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	            // 发送POST请求必须设置如下两行
	            conn.setDoOutput(true);
	            conn.setDoInput(true);
	            // 获取URLConnection对象对应的输出流
	            out = new PrintWriter(conn.getOutputStream());
	            // 发送请求参数
	            out.print(param);
	            // flush输出流的缓冲
	            out.flush();
	            // 定义BufferedReader输入流来读取URL的响应
	            in = new BufferedReader(
	                    new InputStreamReader(conn.getInputStream()));
	            String line;
	            while ((line = in.readLine()) != null) {
	                result += line;
	            }
	        } catch (Exception e) {
	            System.out.println("发送 POST 请求出现异常！"+e);
	            e.printStackTrace();
	        }
	        //使用finally块来关闭输出流、输入流
	        finally{
	            try{
	                if(out!=null){
	                    out.close();
	                }
	                if(in!=null){
	                    in.close();
	                }
	            }
	            catch(IOException ex){
	                ex.printStackTrace();
	            }
	        }
	        return result;
	    }    
	}
class VmInstanceEoExEntity {
	private String uuid;
	private String resourceId;
	private String resourceType;
	private String poolId; // 资源池ID
	private String belongUserId; // 所属用户
	private String projectId; // 所属业务
	private Date expireDate; // 过期时间
	private String woId; // 工单ID
	private String jobId;
	private String jobState;
	private String jobDescription;
	
	
	
	
	public String getJobDescription() {
		return jobDescription;
	}
	public void setJobDescription(String jobDescription) {
		this.jobDescription = jobDescription;
	}
	public String getJobId() {
		return jobId;
	}
	public void setJobId(String jobId) {
		this.jobId = jobId;
	}
	public String getJobState() {
		return jobState;
	}
	public void setJobState(String jobState) {
		this.jobState = jobState;
	}
	public String getUuid() {
		return uuid;
	}
	public void setUuid(String uuid) {
		this.uuid = uuid;
	}
	public String getPoolId() {
		return poolId;
	}
	public void setPoolId(String poolId) {
		this.poolId = poolId;
	}
	public String getResourceId() {
		return resourceId;
	}
	public void setResourceId(String resourceId) {
		this.resourceId = resourceId;
	}
	public String getResourceType() {
		return resourceType;
	}
	public void setResourceType(String resourceType) {
		this.resourceType = resourceType;
	}
	public String getBelongUserId() {
		return belongUserId;
	}
	public void setBelongUserId(String belongUserId) {
		this.belongUserId = belongUserId;
	}
	public String getProjectId() {
		return projectId;
	}
	public void setProjectId(String projectId) {
		this.projectId = projectId;
	}
	public Date getExpireDate() {
		return expireDate;
	}
	public void setExpireDate(Date expireDate) {
		this.expireDate = expireDate;
	}
	public String getWoId() {
		return woId;
	}
	public void setWoId(String woId) {
		this.woId = woId;
	}
}
